package com.echovin.esb.gateway.exception;

import com.echovin.esb.gateway.constants.ErrorCode;
import com.echovin.esb.gateway.model.ResultBody;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

/**
 * 异常信息对应为resultBody
 *
 */
public class GlobalExceptionResolve {

    /**
     * 静态解析异常。可以直接调用
     *
     * @param ex
     * @return
     */
    public static ResultBody resolveException(Throwable ex, String path) {
        int code = ErrorCode.ERROR.getCode();
        String message = ErrorCode.ERROR.getMessage();
        int httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();

        if (ex instanceof ResponseStatusException) {
            code = ErrorCode.NOT_FOUND.getCode();
            if (!StringUtils.isEmpty(ex.getMessage())) {
                message = ex.getMessage();
            }
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            httpStatus = responseStatusException.getStatus().value();
        } else if (ex instanceof OpenException) {
            code = ((OpenException) ex).getCode();
            if (!StringUtils.isEmpty(ex.getMessage())) {
                message = ex.getMessage();
            } else if(!StringUtils.isEmpty(ErrorCode.getMessage(code))) {
                message = ErrorCode.getMessage(code);
            }
            httpStatus = HttpStatus.BAD_REQUEST.value();
        } else {
            if (!StringUtils.isEmpty(ex.getMessage())) {
                message = ex.getMessage();
            }
        }

        return buildBody(code, message, path, httpStatus);
    }

    /**
     * 构建返回结果对象
     *
     * @param code
     * @param message
     * @param path
     * @param httpStatus
     * @return
     */
    private static ResultBody buildBody(int code, String message, String path, int httpStatus) {
        ResultBody resultBody = ResultBody.failed().code(code).msg(message).path(path).httpStatus(httpStatus).data(null);
        return resultBody;
    }

}
